package rusefi;

import java.io.*;
import java.nio.file.*;
import java.util.Date;

public class Bin2Header {
    private static final String NL = "\n";//System.getProperty("line.separator");
    private final static char[] hexChars = "0123456789abcdef".toCharArray();

    private Bin2Header() {
    }

    public static void main(String[] args) throws IOException {
        if (args.length < 3) {
            System.out.println("This tool converts a binary file to C/C++ header file");
            System.out.println("usage:");
            System.out.println("Bin2Header in_file.bin out_file.h arrayVariableDecl");
            return;
        }

        String binFile = args[0];
        String hFile = args[1];
        String arrayVariableDecl = args[2];

        System.out.println("Converting " + binFile + " into " + hFile);

        // This will reference one line at a time
        String line = null;

        
        BufferedWriter bw = new BufferedWriter(new FileWriter(hFile));
        Path path = Paths.get(binFile);
        byte[] data =  Files.readAllBytes(path);

        String headerTag = hFile;
        int pos = headerTag.lastIndexOf("/");
		if (pos >= 0)
    		headerTag = headerTag.substring(pos + 1);
    	headerTag = headerTag.toUpperCase().replace(".", "_") + "_";

        bw.write("// This file was generated by Bin2Header" + NL);
        bw.write("// " + new Date() + NL);
        bw.write("#ifndef " + headerTag + NL);
        bw.write("#define " + headerTag + NL + NL);
 
        bw.write(arrayVariableDecl + " = {");

		for (int i = 0; i < data.length; i++) {
			if ((i & 0xf) == 0)
				bw.write(NL + "\t");
			int b = data[i] & 0xFF;
			bw.write("0x");
        	bw.write(hexChars[b >>> 4]);
        	bw.write(hexChars[b & 0xf]);
        	bw.write(", ");
		}   

        bw.write(NL + "};" + NL + NL);
        bw.write("#endif /* " + headerTag + " */" + NL + NL);
        bw.close();
    }
 
}
